<template>
  <div class="app-container">
    <!-- 课程信息表单 -->
    <el-form label-width="120px">
      <el-form-item label="课程标题：">
        <el-input v-model="courseInfo.title" clearable style="width: 50%"/>
      </el-form-item>

      <!-- 课程讲师 -->
      <el-form-item label="课程讲师：">
        <el-select v-model="courseInfo.teacherId" placeholder="请选择" clearable>
          <el-option v-for="teacher in teacherList"
                     :key="teacher.id"
                     :label="teacher.name"
                     :value="teacher.id"
          />
        </el-select>
      </el-form-item>

      <!-- 所属分类 -->
      <el-form-item label="所属分类：">
          <el-select v-model="courseInfo.subjectParentId" placeholder="请选择" clearable @change="subjectChange">
            <el-option v-for="subject in subjectList"
                       :key="subject.id"
                       :label="subject.title"
                       :value="subject.id"
              />
          </el-select>
          <el-select v-model="courseInfo.subjectId">
              <el-option v-for="item in subjectLevelTwoList"
                         :key="item.id"
                         :label="item.title"
                         :value="item.id"
              />
          </el-select>
      </el-form-item>
      <el-form-item label="总课时：">
        <el-input-number :min="0" v-model="courseInfo.lessonNum" controls-position="right"/>
      </el-form-item>

      <!-- 课程简介 -->
      <el-form-item label="课程简介：">
        <tinymce :height="300" v-model="courseInfo.description"></tinymce>
      </el-form-item>

      <!-- 课程封面-->
      <el-form-item label="课程封面：">
        <el-upload
          class="cover-uploader"
          :show-file-list="false"
          :on-success="handleCoverSuccess"
          :before-upload="beforeCoverUpload"
          :on-error="handleCoverError"
          :action="BASE_API+'/admin/oss/file/upload?module=cover'">
          <img v-if="courseInfo.cover" :src="courseInfo.cover">
          <i v-else class="el-icon-plus avatar-uploader-icon"/>
        </el-upload>
      </el-form-item>


      <el-form-item label="课程价格：">
        <el-input-number :min="0" v-model="courseInfo.price" controls-position="right" placeholder="免费课程请设置为0元"/> 元
      </el-form-item>
    </el-form>



    <div style="text-align: center">
        <el-button :disabled="saveBtnDisabled" type="primary" @click="saveAndNext()">保存并下一步</el-button>
    </div>
  </div>
</template>

<script>
import courseApi from "@/api/course";
import teacherApi from "@/api/teacher";
import subjectApi from "@/api/subject";
import Tinymce from '@/components/Tinymce'
import subject from '../../../api/subject'
export default {
  components: {Tinymce},
  name: "info",
  data() {
    return{
      saveBtnDisabled: false,
      BASE_API: process.env.BASE_API,
      courseInfo: {
        price: 0,
        lessonNum: 0,
        // 以下解决表单数据不全时insert语句非空校验
        teacherId: '',
        subjectId: '',
        subjectParentId: '',
        cover: '',
        description: ''
      },
      teacherList: [], //讲师列表
      subjectList: [],//一级分类列表
      subjectLevelTwoList: [],//二级分类列表
    }
  },
  created() {
    this.initTeacherList()
    this.initSubjectList()
    if (this.$parent.courseId){
      this.fetchCourseInfoById(this.$parent.courseId)
    }
  },
  methods: {
    saveAndNext() {
      this.saveBtnDisabled = true
      if (!this.$parent.courseId) {
        this.saveData()
      } else {
        this.updateDate()
      }
    },
    //更新数据就不会进行下一步，直接调用保存就可以了
    updateDate() {
      courseApi.updateCourseInfoById(this.courseInfo).then(res => {
        this.$message.success(res.message)
      })
    },
    saveData() {
      courseApi.saveCourseInfo(this.courseInfo).then(res => {
        this.$message.success(res.message)
        this.$parent.courseId = res.data.courseId //给其他组件传递保存的Id
        this.$parent.active = '1'
      })
    },
    initTeacherList() {
      teacherApi.list().then(res => {
        this.teacherList = res.data.items
      })
    },
    initSubjectList() {
      subjectApi.getNestedTreeList().then(res => {
        this.subjectList = res.data.items
      })
    },
    subjectChange(val) {
      console.log("val",val)
      this.subjectList.forEach(subject => {
        if (subject.id == val) {
          //重新选值之后就清空后面列表
          this.courseInfo.subjectId = ''
          this.subjectLevelTwoList = subject.children
        }
      })
    },
    //上传成功回调函数
    handleCoverSuccess(res) {
        if (res.success) {
          this.$message.success("上传成功")
          this.courseInfo.cover = res.data.url
          // 强制重新渲染
          this.$forceUpdate()
        } else {
          this.$message.error("上传失败")
        }
    },
    //上传之前的校验
    beforeCoverUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    //上传的错误显示
    handleCoverError() {

    },
    fetchCourseInfoById(id) {
      courseApi.getCourseInfoById(id).then(res => {
        this.courseInfo = res.data.item
        subjectApi.getNestedTreeList().then(res => {
            this.subjectList = res.data.items
            this.subjectList.forEach(subject => {
              if (subject.id == this.courseInfo.subjectParentId) {
                this.subjectLevelTwoList = subject.children
              }
            })
        })
      })
    },
  }
}
</script>

<style scoped>
.tinymce-container {
  position: relative;
  line-height: normal;
}
.cover-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.cover-uploader .el-upload:hover {
  border-color: #409EFF;
}
.cover-uploader .avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 640px;
  height: 357px;
  line-height: 357px;
  text-align: center;
}
.cover-uploader img {
  width: 640px;
  height: 357px;
  display: block;
}
</style>
